#!/usr/bin/env python
# encoding: utf-8
'''
two2one -- shortdesc

two2one is a description

It defines classes_and_methods

@author:     user_name
            
@copyright:  2013 organization_name. All rights reserved.
            
@license:    license

@contact:    user_email
@deffield    updated: Updated
'''

import sys
import os, shutil, re

from optparse import OptionParser

__all__ = []
__version__ = 0.1
__date__ = '2013-04-09'
__updated__ = '2013-04-09'

DEBUG = 0
TESTRUN = 0
PROFILE = 0

def print_action(one, two):
    print "Moving '{0}' to '{1}'".format(one, two)
    shutil.move(one, two)

def two2one(one, two, out, fn=shutil.move):
    if not os.path.isdir(one) or not os.path.isdir(two):
        return
    fn(one, out)
    regexp = re.compile('(\d*)_(.*)')
    idmax = 0
    for f in os.listdir(out):
        m = regexp.match(f)
        if m and int(m.group(1)) > idmax:
            idmax = int(m.group(1)) 
    files_to_copy = []
    for f in os.listdir(two):
        m = regexp.match(f)
        if m:
            files_to_copy.append(f)
        else:
            fn(two+'/'+f, out)
    files_to_copy.sort()
    for f in files_to_copy:
        m = regexp.match(f)
        fn(two+'/'+f, "{0}/{1:2d}_{2}".format(out, idmax+int(m.group(1)), m.group(2)))
    os.rmdir(two)

def main(argv=None):
    '''Command line options.'''
    
    program_name = os.path.basename(sys.argv[0])
    program_version = "v0.1"
    program_build_date = "%s" % __updated__
 
    program_version_string = '%%prog %s (%s)' % (program_version, program_build_date)
    #program_usage = '''usage: spam two eggs''' # optional - will be autogenerated by optparse
    program_longdesc = '''''' # optional - give further explanation about what the program does
    program_license = "Copyright 2013 user_name (organization_name)                                            \
                Licensed under the Apache License 2.0\nhttp://www.apache.org/licenses/LICENSE-2.0"
 
    if argv is None:
        argv = sys.argv[1:]
    try:
        # setup option parser
        parser = OptionParser(version=program_version_string, epilog=program_longdesc, description=program_license)
#        parser.add_option("-i", "--in", dest="infile", help="set input path [default: %default]", metavar="FILE")
#        parser.add_option("-o", "--out", dest="outfile", help="set output path [default: %default]", metavar="FILE")
        parser.add_option("-v", "--verbose", dest="verbose", action="count", help="set verbosity level [default: %default]")
        
        # set defaults
#        parser.set_defaults(outfile="./out.txt", infile="./in.txt")
        
        # process options
        (opts, args) = parser.parse_args(argv)
        
        if opts.verbose > 0:
            print("verbosity level = %d" % opts.verbose)
        if len(args) != 3:
            print("{0} need 3 parameters : first & second input folders and output folder".format(program_name))
            return
        # MAIN BODY #
        two2one(args[0], args[1], args[2], print_action)
        
    except ZeroDivisionError, e:
        indent = len(program_name) * " "
        sys.stderr.write(program_name + ": " + repr(e) + "\n")
        sys.stderr.write(indent + "  for help use --help")
        return 2


if __name__ == "__main__":
    if DEBUG:
        sys.argv.append("-h")
    if TESTRUN:
        import doctest
        doctest.testmod()
    if PROFILE:
        import cProfile
        import pstats
        profile_filename = 'two2one_profile.txt'
        cProfile.run('main()', profile_filename)
        statsfile = open("profile_stats.txt", "wb")
        p = pstats.Stats(profile_filename, stream=statsfile)
        stats = p.strip_dirs().sort_stats('cumulative')
        stats.print_stats()
        statsfile.close()
        sys.exit(0)
    sys.exit(main())